//  this library.
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:hktk_app/dao/login_dao.dart';
import 'package:hktk_app/ienum/my/asset_status_enum.dart';
import 'package:hktk_app/ienum/my/asset_type_enum.dart';
import 'package:hktk_app/ienum/practice/ct_enum.dart';
import 'package:hktk_app/ienum/question/first_type_enum.dart';
import 'package:hktk_app/ienum/subject/collection_type_enum.dart';
import 'package:hktk_app/ienum/subject/paper_type_enum.dart';
import 'package:hktk_app/model/industry/category_model.dart';
import 'package:hktk_app/model/login/user_info_model.dart';
import 'package:hktk_app/model/practice/practice_question_model.dart';
import 'package:hktk_app/model/question/question_data_model.dart';
import 'package:hktk_app/util/view_util.dart';

/// 对应方法
class MyUtil {
  /// 判断是否过期方法
  static bool getExpire(String yxqStr) {
    DateTime yxq = DateTime.parse(yxqStr);
    DateTime now = DateTime.now();
    return now.isBefore(yxq);
  }

  /// 获取格式化的有效期字符串
  static String getValidity(String yxqStr) {
    DateTime yxq = DateTime.parse(yxqStr);
    String year = yxq.year.toString();
    String month = getDateStr(yxq.month);
    String day = getDateStr(yxq.day);
    String hour = getDateStr(yxq.hour);
    String minute = getDateStr(yxq.minute);
    return "$year-$month-$day $hour:$minute";
  }

  /// 获取剩余天数方法
  static int getSurplusDay(String yxqStr) {
    DateTime yxq = DateTime.parse(yxqStr);
    DateTime now = DateTime.now();
    Duration difference = yxq.difference(now);
    return difference.inDays;
  }

  /// 获取按钮组件方法
  static Widget getBtnItem({
    required BuildContext context,
    required AssetStatusEnum efficientStatus,
    required Function(BuildContext context,AssetTypeEnum type) onTapFun,
    AssetTypeEnum type=AssetTypeEnum.question,
  }) {
    String btnStr;
    bool unexpired = false;
    if (efficientStatus == AssetStatusEnum.effective) {
      btnStr = "前往学习";
      unexpired = true;
    } else if (efficientStatus == AssetStatusEnum.invalid) {
      btnStr = "立即支付";
    } else {
      btnStr = "立即续费";
    }
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        GestureDetector(
          onTap: () {
            // 需要指定具体的页面，增强体验
            onTapFun(context,type);
          },
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
            decoration: BoxDecoration(
              color: unexpired ? colorBlue1 : colorYellow1,
              borderRadius: BorderRadius.circular(30),
            ),
            child: Center(
              child: Text(
                btnStr,
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: unexpired ? FontWeight.w400 : FontWeight.w500,
                  color: unexpired ? colorWhite1 : colorBrown1,
                ),
              ),
            ),
          ),
        )
      ],
    );
  }

  /// 根据科目数据获取选中的数据
  static List<CategoryModel> getSelList(List<CategoryModel> list) {
    List<CategoryModel> selList = [];
    for (CategoryModel model in list) {
      if (model.isSelect!) {
        selList.add(model);
      }
    }
    return selList;
  }

  /// 根据科目数据获取对应的数据，需要提交的
  static List<Map<String, dynamic>> getSelectSubject({
    required List<CategoryModel> subjectList,
    int index = 0,
  }) {
    List<Map<String, dynamic>> list = [];
    int i = 0;
    for (CategoryModel model in subjectList) {
      if (model.isSelect!) {
        Map<String, dynamic> map = {"categoryId": model.id, "check": false};
        if (index == i) {
          map["check"] = true;
        }
        list.add(map);
        i++;
      }
    }
    return list;
  }

  /// 判断是否是单选题
  static bool getDXT(FirstTypeEnum type) {
    return type == FirstTypeEnum.singleChoice;
  }

  /// 判断是否是多项选择题
  static bool getDXXZT(FirstTypeEnum type) {
    return type == FirstTypeEnum.multipleChoice;
  }

  /// 判断是否是判断题
  static bool getPDT(FirstTypeEnum type) {
    return type == FirstTypeEnum.judgment;
  }

  /// 判断是否是填空题
  static bool getTKT(FirstTypeEnum type) {
    return type == FirstTypeEnum.fill;
  }

  /// 判断是否是问答题
  static bool getWDT(FirstTypeEnum type) {
    return type == FirstTypeEnum.text;
  }

  /// 判断是否是不定项选择题
  static bool getBDXXZT(FirstTypeEnum type) {
    return type == FirstTypeEnum.indefiniteMultipleChoice;
  }

  /// 将试题解析成通用格式方法
  static QuestionDataModel getQuestionData(PracticeQuestionModel model) {
    // 题型
    FirstTypeEnum typeEnum = model.firstType!;
    // 选项
    List<OptionModel> list = _getOptionList(model.quOption, typeEnum);
    // 答案
    List<String> answer = _getAnswerStr(model.rightAnswer, typeEnum);
    // 解析
    String analysis = getStemStr(model.answerDesc);

    return QuestionDataModel(
      id: model.id!,
      type: typeEnum,
      stem: model.stem,
      optionList: list,
      answer: answer,
      answerBase64: model.answerBase64,
      analysis: analysis,
      sign: model.sign!,
      record: model.record,
      collect: model.collect,
      doingNumber: model.doingNumber ?? 0,
      errorNumber: model.errorNumber ?? 0,
    );
  }

  /// 解析对应数据
  static String getStemStr(List<Stem>? stemList) {
    String str = "";
    stemList?.forEach((Stem stem) {
      str += stem.vl!;
    });

    return str;
  }

  /// 获取答案
  static List<String> _getAnswerStr(dynamic answer, FirstTypeEnum type) {
    List<String> list = [];
    if (answer == null) {
      return list;
    }
    if (MyUtil.getDXT(type) || MyUtil.getPDT(type)) {
      list.add(answer.toString());
    } else if (MyUtil.getDXXZT(type) || MyUtil.getBDXXZT(type)) {
      if (answer is List<dynamic>) {
        list = answer.map((dynamic ans) => ans.toString()).toList();
      }
    } else if (MyUtil.getTKT(type) || MyUtil.getWDT(type)) {
      list = _getAnsPDT(answer);
    }
    return list;
  }

  /// 获取判断题相关数据
  static List<String> _getAnsPDT(dynamic answer) {
    List<String> list = [];
    String str = "";

    if (answer is List<dynamic>) {
      for (var v1 in answer) {
        if (v1["vl"] != null) {
          var v1Vl = v1["vl"];
          if (v1Vl is List<dynamic>) {
            for (var v2 in v1Vl) {
              if (v2["vl"] != null) {
                str = v2["vl"].toString();
              }
            }
          }
        }
      }
    }
    list = str.split(" ");
    return list;
  }

  /// 获取选项相关数据
  static List<OptionModel> _getOptionList(
      List<dynamic>? option, FirstTypeEnum type) {
    List<OptionModel> list = [];
    if (MyUtil.getDXT(type) ||
        MyUtil.getDXXZT(type) ||
        MyUtil.getPDT(type) ||
        MyUtil.getBDXXZT(type)) {
      list = _getQpXZT(option!);
    } else if (MyUtil.getTKT(type) || MyUtil.getWDT(type)) {
      list = _getOpTKT(option!);
    }
    return list;
  }

  /// 获取选择/问答相关选项数据
  static List<OptionModel> _getQpXZT(List<dynamic> list) {
    List<OptionModel> opList = [];
    for (Map<String, dynamic> map in list) {
      QuOption quOption = QuOption.fromJson(map);
      String con = getStemStr(quOption.content);
      opList.add(OptionModel(
        option: quOption.option!.toString(),
        content: con,
      ));
    }
    return opList;
  }

  /// 获取填空/问题相关选项数据
  static List<OptionModel> _getOpTKT(List<dynamic> list) {
    return list.map((e) => OptionModel(option: "", content: "")).toList();
  }

  /// 用户答案解析成固定格式
  static List<String> getUserAnsList(dynamic ans, FirstTypeEnum type) {
    List<String> list = [];
    if (getDXT(type) || getPDT(type)) {
      list.add(ans.toString());
    } else {
      if (ans is List<dynamic>) {
        list = ans.map((e) => e.toString()).toList();
      } else if (ans is String) {
        List<dynamic> list2 = jsonDecode(ans);
        list = list2.map((e) => e.toString()).toList();
      }
    }
    return list;
  }

  /// 用户答案解析成固定格式
  static String getUserAnsStr(List<String> ans, FirstTypeEnum type) {
    String str = jsonEncode(ans);
    if (getDXT(type) || getPDT(type)) {
      str = ans[0];
    }
    return str;
  }

  /// 获取试题对应格式题干
  static String getQuesStemStr({
    List<Stem>? stem,
    required FirstTypeEnum type,
  }) {
    String tg = MyUtil.getStemStr(stem);
    String tx = "<p></p><span style=\"color=#FFBB00\";>[${type.desc}]</span> ";
    int index = tg.indexOf("<p>");
    if (index != -1) {
      tg = tg.substring(index + 3);
    }
    return tx + tg;
  }

  /// 返回对应类型
  static CollectionTypeEnum getCollTypeEnum(CtEnum ctEnum) {
    CollectionTypeEnum typeEnum = CollectionTypeEnum.hotQue;
    switch (ctEnum) {
      case CtEnum.chapter:
        typeEnum = CollectionTypeEnum.chapter;
        break;
      case CtEnum.everyday:
        typeEnum = CollectionTypeEnum.everyDayPractice;
        break;
      case CtEnum.rankError:
        typeEnum = CollectionTypeEnum.rankError;
        break;
      case CtEnum.rankCollect:
        typeEnum = CollectionTypeEnum.rankCollect;
        break;
      case CtEnum.paperRecordChapterPractice:
      case CtEnum.paperRecordPaperLibrary:
        typeEnum = CollectionTypeEnum.paper;
        break;
      case CtEnum.paperRecordSpecialPractice:
      case CtEnum.paperRecordRandomFormPaper:
      case CtEnum.paperRecordErrorCombination:
      case CtEnum.hotQue:
        typeEnum = CollectionTypeEnum.hotQue;
        break;
    }

    return typeEnum;
  }

  /// 获取试卷类型
  static String getPaperType(PaperTypeEnum type) {
    return type.desc.substring(0, 2);
  }

  /// 每日一练判断题型
  static FirstTypeEnum getTypeEnum(String type) {
    if (type == "单选题") {
      return FirstTypeEnum.singleChoice;
    } else if (type == "多项选择题") {
      return FirstTypeEnum.multipleChoice;
    } else if (type == "判断题") {
      return FirstTypeEnum.judgment;
    } else if (type == "填空题") {
      return FirstTypeEnum.fill;
    } else if (type == "问答题") {
      return FirstTypeEnum.text;
    }
    return FirstTypeEnum.singleChoice;
  }
}

/// 保存登录token方法
void saveTokenFun(String token) {
  HiCache.getInstance().setString(LoginDao.getSaveTokenKey(), token);
}

/// 获取登录token方法
String? getToken() {
  return HiCache.getInstance().get(LoginDao.getSaveTokenKey());
}

/// 保存用户信息方法
void saveUserInfoFun(UserInfoModel userInfoModel) {
  String ss = jsonEncode(userInfoModel);
  HiCache.getInstance().setString(LoginDao.getSaveUserKey(), ss);
}

/// 获取用户信息方法
UserInfoModel getUserInfo() {
  String? con = HiCache.getInstance().get(LoginDao.getSaveUserKey());
  if (con != null) {
    var decode = jsonDecode(con);
    return UserInfoModel.fromJson(decode);
  }
  return UserInfoModel(id: "", name: "", mobile: "", header: "");
}

/// 退出登录
void loginOut(BuildContext context) {
// 移除登录保存的信息
  HiCache.getInstance().remove(LoginDao.getSaveTokenKey());
  HiCache.getInstance().remove(LoginDao.getSaveUserKey());
// 路由跳转，跳转登录页
  Navigator.pushNamedAndRemoveUntil(context, "/login", (route) => false);
}

/// 验证是否是游客模式
bool visitorMode() {
  return getToken() == null;
}
